package com.greendragon.web.action.account;

import java.util.Date;

import com.greendragon.control.constant.GlobalConstants;
import com.greendragon.persistence.domain.User;
import com.greendragon.persistence.enmu.UserRoleType;
import com.greendragon.service.frontend.IUserFrontendService;
import com.greendragon.util.CookieUtil;
import com.greendragon.util.TokenUtil;
import com.greendragon.web.action.BaseAction;

/**
 * @author wulibin, exceptsky@gmail.com, 2011-11-9 下午08:24:53
 * 
 */
public class LoginAction extends BaseAction {
	private static final long serialVersionUID 	= 		-9185704050786970475L;
	private static final String ADMIN			=		"admin";
	private IUserFrontendService userService;
	private String name;
	private String password;
	private boolean rememberMe;

	public String execute() throws Exception {
		User user = userService.login(name, password);
		if (null == user) {
			// 登入失败，密码或用户名错误
			addFieldError("name", getText("nameorpassword.fail"));
			return INPUT;
		} else {
			// 记住登入状态
			if (rememberMe) {
				String token = TokenUtil.makeToken(user.getId() + "");
				// 保存7天
				int expires = 60 * 60 * 24 * 7;
				CookieUtil.addCookie(getResponse(),
						GlobalConstants.COOKIE_REMEMBER_ME, token, expires);
			} else {
				CookieUtil.removeCookie(getResponse(),
						GlobalConstants.COOKIE_REMEMBER_ME);
			}

			user.setLastLoginAt(new Date());
			user.setLastLoginIp(getRequest().getRemoteHost());
			userService.update(user);
			getSession().put(GlobalConstants.SESSION_LOGIN_USER, user);
			if(user.getRole().equals(UserRoleType.ADMIN.getName()) || 
					user.getRole().equals(UserRoleType.SUPERADMIN.getName())){
				return ADMIN;
			}else{
				return LOGIN;
			}
		}
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

	public void setUserService(IUserFrontendService userService) {
		this.userService = userService;
	}

	public String getName() {
		return name;
	}

	public String getPassword() {
		return password;
	}

}
